export = {};

/** 应该从类型安全方面去考虑 兼容性的实现策略*/

/** 1. 鸭式变形法*/
interface Human {
  name: string;
  age: number;
}

// let h: Human = {name: 'ahhh', age: 123, gender: 'male'}; // TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'Human'.   Object literal may only specify known properties, and 'gender' does not exist in type 'Human'.
/* ↑
我们在讲接口时已经讲过 字面量的形式会经过额外的类型检查 不允许鸭式变形*/

// 但如果是间接通过变量赋值,则支持鸭式变形
let t = {name: 'ahhh', age: 123, gender: 1};
let h: Human = t;

/** 之所以ts要实现这种兼容性是因为:*/
// 如果我们想让一个x在普通情况下被赋予不同类型的值
// 我们需要像下面这样写 很麻烦
interface H extends Human{
  grade?: number;
  sex?: number;
}
let x: H;
let y = {name: 'Ahhh', age: 123, grade: 1};
let z = {name: 'Ahhh', age: 123, sex: 1};
let n = Math.random();
if(n>.5){
  x = y;
}else{
  x = z;
}


/** 2. 联合类型*/
//但并不是属性多 就可以赋给属性少的(鸭式变形法),
//比如联合类型的情况
let str!: string;
let temp!: string | number;

// temp = str
str = temp
//TS2322: Type 'string | number' is not assignable to type 'string'.
// Type 'number' is not assignable to type 'string'.
